<template>
  <div class="tasklist-page">
    <!-- 顶部筛选区（含搜索、优先级、标签） -->
    <div class="filter-row filter-row-with-search">
      <el-input
        v-model="searchQuery"
        placeholder="搜索任务..."
        class="search-input custom-search"
        clearable
        :prefix-icon="Search"
      />
      <el-button class="search-btn" type="primary" @click="onSearch"><template #icon><Search /></template>搜索</el-button>
      <el-button class="reset-btn" @click="onReset">重置</el-button>
      <span class="filter-label">优先级：</span>
      <span
        v-for="priority in priorityOptions"
        :key="priority.value"
        :class="['priority-chip', priority.value, { active: selectedPriority === priority.value }]"
        @click="selectedPriority = selectedPriority === priority.value ? '' : priority.value"
      >
        {{ priority.label }}
      </span>
      <span class="filter-label" style="margin-left:16px;">标签：</span>
      <span
        v-for="tag in tags"
        :key="tag.id"
        :class="['tag-chip', { active: selectedTag === tag.id, green: tag.color === '#52c41a', gray: tag.color !== '#52c41a' }]"
        @click="selectedTag = selectedTag === tag.id ? '' : tag.id"
        :style="tag.color === '#52c41a' ? { backgroundColor: '#f6ffed', color: '#52c41a', border: 'none' } : { backgroundColor: '#f5f5f5', color: '#888', border: 'none' }"
      >
        {{ tag.name }}
      </span>
    </div>
    <!-- 任务列表 -->
<!--    @click="showTaskDetail(task.id)"-->
    <div class="tasklist-content">
      <div
        v-for="task in filteredTasks"
        :key="task.id"
        class="task-card"
        style="position: relative;"
      >
        <el-checkbox
          class="task-complete-checkbox"
          :model-value="task.status === 'C'"
          @change="val => onToggleComplete(task, val)"
          @click.stop
        />
        <div class="task-card-left" :style="{ background: getPriorityColor(task.priority) }"></div>
        <div class="task-card-main">
          <div class="task-title-row">
            <span class="task-title" :class="{ 'completed': task.status === 'C' }">{{ task.title }}</span>
            <el-tag
              :type="getPriorityType(task.priority)"
              class="priority-tag"
              effect="plain"
            >
              {{ getPriorityLabel(task.priority) }}优先级
            </el-tag>
          </div>
          <div class="task-meta-row">
            <span class="task-date">截止日期：{{ formatDate(task.due_date) }}</span>
            <el-tag
              v-for="tag in task.tags"
              :key="tag.id"
              :style="{ backgroundColor: tag.color, color: '#fff', border: 'none' }"
              class="meta-tag"
              effect="plain"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
        <div class="task-card-actions">
          <el-button size="small" type="primary" @click.stop="showTaskDetail(task.id)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button size="small" type="danger" @click.stop="onDeleteTask(task.id)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
      </div>
      <div v-if="filteredTasks.length === 0" class="empty-tip">暂无任务</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import http from '../utils/http'

const tasks = ref([])
const searchQuery = ref('')
const selectedPriority = ref('')
const selectedTag = ref('')

const priorityOptions = [
  { label: '高', value: 'H', color: '#ff4d4f', bg: '#ffeaea', text: '#ff4d4f' },
  { label: '中', value: 'M', color: '#faad14', bg: '#fff7e6', text: '#faad14' },
  { label: '低', value: 'L', color: '#52c41a', bg: '#f6ffed', text: '#52c41a' }
]

const tags = ref([])

const fetchTasks = async () => {
  try {
    const response = await http('/api/tasks')
    const data = await response.json()
    tasks.value = data.results
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  }
}

const fetchTags = async () => {
  try {
    const response = await http('/api/tags')
    const data = await response.json()
    tags.value = data.results
  } catch (error) {
    ElMessage.error('获取标签失败')
  }
}

const getPriorityType = (priority) => {
  const map = { H: 'danger', M: 'warning', L: 'success' }
  return map[priority] || 'info'
}
const getPriorityLabel = (priority) => {
  const map = { H: '高', M: '中', L: '低' }
  return map[priority] || '未知'
}
const getPriorityColor = (priority) => {
  const map = { H: '#ff4d4f', M: '#faad14', L: '#52c41a' }
  return map[priority] || '#d9d9d9'
}
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toISOString().slice(0, 10)
}

const filteredTasks = computed(() => {
  return tasks.value.filter(task => {
    const matchesSearch = !searchQuery.value || task.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesPriority = !selectedPriority.value || task.priority === selectedPriority.value
    const matchesTag = !selectedTag.value || task.tags.some(tag => tag.id === selectedTag.value)
    return matchesSearch && matchesPriority && matchesTag
  })
})

function onSearch() {
  // 这里可以触发过滤逻辑或请求
}
function onReset() {
  searchQuery.value = ''
  selectedPriority.value = ''
  selectedTag.value = ''
}

const emit = defineEmits(['show-detail'])

function showTaskDetail(id) {
  emit('show-detail', id)
}

function onDeleteTask(id) {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const res = await http(`/api/tasks/${id}`, { method: 'DELETE' })
      if (!res.ok) throw new Error('删除失败')
      ElMessage.success('删除成功')
      fetchTasks()
    } catch {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

function onToggleComplete(task, checked) {
  if (checked) {
    // 标记为完成
    http(`/api/tasks/${task.id}/complete`, { method: 'POST' })
      .then(res => {
        if (!res.ok) throw new Error()
        fetchTasks()
        ElMessage.success('已标记为完成')
      })
      .catch(() => ElMessage.error('操作失败'))
  } else {
    // 标记为未完成
    http(`/api/tasks/${task.id}/uncomplete`, { method: 'POST' })
      .then(res => {
        if (!res.ok) throw new Error()
        fetchTasks()
        ElMessage.success('已标记为未完成')
      })
      .catch(() => ElMessage.error('操作失败'))
  }
}

onMounted(() => {
  fetchTasks()
  fetchTags()
})
</script>

<style scoped>
.tasklist-page {
  padding: 0;
  min-height: 100vh;
  background: #f7f8fa;
}
.filter-row-with-search {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #fff;
  padding: 24px 0 24px 32px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 64px;
}
.custom-search {
  flex: none;
  width: 320px;
  background: #fafbfc;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  height: 36px;
  font-size: 15px;
  margin-right: 12px;
}
.custom-search :deep(.el-input__wrapper) {
  background: #fafbfc;
  border-radius: 6px;
  border: none;
  box-shadow: none;
}
.search-btn {
  margin-right: 8px;
  height: 36px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 500;
  padding: 0 18px;
  display: flex;
  align-items: center;
}
.reset-btn {
  height: 36px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 500;
  padding: 0 18px;
  margin-right: 18px;
  background: #f5f5f5;
  color: #888;
  border: 1px solid #e4e7ed;
}
.reset-btn:hover {
  background: #f0f0f0;
  color: #222;
}
.filter-label {
  color: #b0b0b0;
  font-size: 14px;
  margin-right: 6px;
}
.priority-chip {
  display: inline-block;
  min-width: 32px;
  text-align: center;
  font-size: 14px;
  border-radius: 6px;
  padding: 0 10px;
  margin-right: 6px;
  cursor: pointer;
  border: none;
  transition: box-shadow 0.2s;
  height: 28px;
  line-height: 28px;
  font-weight: 500;
}
.priority-chip.H {
  background: #ffeaea;
  color: #ff4d4f;
}
.priority-chip.M {
  background: #fff7e6;
  color: #faad14;
}
.priority-chip.L {
  background: #f6ffed;
  color: #52c41a;
}
.priority-chip.active {
  box-shadow: 0 0 0 2px #409eff33;
}
.tag-chip {
  display: inline-block;
  min-width: 32px;
  text-align: center;
  font-size: 14px;
  border-radius: 6px;
  padding: 0 10px;
  margin-right: 6px;
  cursor: pointer;
  border: none;
  transition: box-shadow 0.2s;
  height: 28px;
  line-height: 28px;
  font-weight: 500;
  background: #f5f5f5;
  color: #888;
}
.tag-chip.green {
  background: #f6ffed;
  color: #52c41a;
}
.tag-chip.active {
  box-shadow: 0 0 0 2px #409eff33;
}
.tasklist-content {
  padding: 32px 32px 0 32px;
}
.task-card {
  display: flex;
  align-items: stretch;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px 0 #e6e6e6;

  min-height: 80px;
  transition: box-shadow 0.2s;
  max-width: 80%;
  position: relative;
  margin:auto;
  margin-bottom: 24px;
}
.task-card-left {
  width: 6px;
  border-radius: 10px 0 0 10px;
  background: #d9d9d9;
}
.task-card-main {
  flex: 1;
  padding: 18px 24px 14px 24px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.task-title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}
.task-title {
  color: #222;
  font-weight: 600;
}
.task-meta-row {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #888;
}
.meta-tag {
  font-size: 13px;
  border-radius: 4px;
  padding: 0 8px;
  border: none;
}
.task-card-actions {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 24px;
  display: flex;
  gap: 8px;
}
.empty-tip {
  text-align: center;
  color: #bbb;
  margin-top: 80px;
  font-size: 18px;
}
.task-complete-checkbox {
  margin-right: 12px;
  margin-left: 4px;
}
.task-title.completed {
  color: #52c41a;
  text-decoration: line-through;
}
</style>
